use std::collections::HashMap;

use clap::{Arg, ArgMatches, Command};

use crate::environment::define::Environment;
use crate::environment::environment;

pub(super) const NAME: &'static str = "get";

pub(super) fn new() -> Command {
    let mut command = Command::new(NAME).about("查看环境变量信息");
    command = command.arg(Arg::new("name").required(true).help("工具名称"));

    command
}

pub(super) fn action(args: &ArgMatches) {
    let name = args.get_one::<String>("name").unwrap();
    let mut environments: HashMap<String, String> = Default::default();

    // 闭包封装代码
    let mut get_environments = |environment: &Environment| {
        if environment.get_environments(name).is_some() {
            for (key, value) in environment.get_environments(name).unwrap().iter() {
                environments.insert(key.to_string(), value.to_string());
            }
        }
    };

    get_environments(environment::global());
    get_environments(environment::project());

    // 排序
    let mut keys: Vec<&String> = environments.keys().collect();
    keys.sort();

    for key in keys {
        let value = environments.get(key).unwrap();

        if "DEMNULL" == value {
            continue;
        }

        println!("{}={}", key, value);
    }
}